<template>
    <div class="export-container">
    <el-card class="export-card">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Document /></el-icon>
          <span>筛查结果</span>
        </div>
      </template>

      <div class="processing-info">
        <el-alert
          type="info"
          :closable="false"
          show-icon
        >
          <div class="info-content">
            <p>系统是按照用户上传的时间顺序进行筛查清洗返回结果文件，一般时几分钟到几个小时内，定期刷新。</p>
          </div>
        </el-alert>
      </div>

      <el-tabs v-model="activeTab" class="export-tabs" @tab-click="handleTabClick">
        <!-- 未完成标签页 -->
        <el-tab-pane label="未完成" name="pending">
          <div class="table-header">
            <div class="header-left">
              <el-icon><Loading /></el-icon>
              <span>处理中的文件</span>
            </div>
            <div class="refresh-btn" @click="refreshPendingList">
              <el-icon><Refresh /></el-icon>
              <span>刷新</span>
            </div>
          </div>

          <el-table :data="pendingFiles" stripe style="width: 100%">
            <el-table-column prop="fileName" label="文件名" min-width="200">
              <template #default="{ row }">
                <div class="file-name">
                  <el-icon><Document /></el-icon>
                  <span>{{ row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="200">
              <template #default="{ row }">
                <div class="status-cell">
                  <el-progress 
                    :percentage="row.progress" 
                    :status="row.progress < 100 ? '' : 'success'"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteFile(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 已完成标签页 -->
        <el-tab-pane label="已完成" name="completed">
          <div class="table-header">
            <div class="header-left">
              <el-icon><Select /></el-icon>
              <span>已完成文件</span>
            </div>
          </div>

          <el-table :data="completedFiles" stripe style="width: 100%">
            <el-table-column prop="fileName" label="文件名" min-width="200">
              <template #default="{ row }">
                <div class="file-name">
                  <el-icon><Document /></el-icon>
                  <span>{{ row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="totalCount" label="总数量" width="120">
              <template #default="{ row }">
                <span class="count-text">{{ row.totalCount }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="downloadFile(row)"
                >
                  <el-icon><Download /></el-icon>
                  下载结果
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 格式错误标签页 -->
        <el-tab-pane label="格式错误" name="error">
          <div class="table-header">
            <div class="header-left">
              <el-icon><Warning /></el-icon>
              <span>格式错误文件</span>
            </div>
          </div>

          <el-table :data="errorFiles" stripe style="width: 100%">
            <el-table-column prop="fileName" label="文件名" min-width="200">
              <template #default="{ row }">
                <div class="file-name">
                  <el-icon><Document /></el-icon>
                  <span>{{ row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="uploadTime" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.uploadTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="errorMsg" label="错误信息" min-width="200">
              <template #default="{ row }">
                <span class="error-text">{{ row.errorMsg }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120" fixed="right">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteFile(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="totalRecords"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    </div>
  </template>
  
  <script setup>
import { ref, watch, onMounted } from 'vue';
import { 
  Document,
  Download,
  Loading,
  Select,
  Warning,
  Refresh
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import {
  getPendingFilesApi,
  getCompletedFilesApi,
  getErrorFilesApi,
  deleteFileApi,
  downloadFileApi
} from '@/api/export';

const activeTab = ref('pending');
const pendingFiles = ref([]);
const completedFiles = ref([]);
const errorFiles = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalRecords = ref(0);

// 格式化日期时间
const formatDateTime = (datetime) => {
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss');
};

// 获取未完成文件
const fetchPendingFiles = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await getPendingFilesApi(pageNum, pageSize);
    // 后端返回格式：Result<IPage>，所以需要从 response.data.data 获取 IPage 对象
    const pageData = response.data.data || {};
    pendingFiles.value = pageData.records || [];
    totalRecords.value = pageData.total || 0;
  } catch (error) {
    ElMessage.error('获取未完成文件失败：' + (error.message || '未知错误'));
    pendingFiles.value = [];
    totalRecords.value = 0;
  }
};

// 获取已完成文件
const fetchCompletedFiles = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await getCompletedFilesApi(pageNum, pageSize);
    // 后端返回格式：Result<IPage>，所以需要从 response.data.data 获取 IPage 对象
    const pageData = response.data.data || {};
    completedFiles.value = pageData.records || [];
    totalRecords.value = pageData.total || 0;
  } catch (error) {
    ElMessage.error('获取已完成文件失败：' + (error.message || '未知错误'));
    completedFiles.value = [];
    totalRecords.value = 0;
  }
};

// 获取格式错误文件
const fetchErrorFiles = async (pageNum = 1, pageSize = 10) => {
  try {
    const response = await getErrorFilesApi(pageNum, pageSize);
    // 后端返回格式：Result<IPage>，所以需要从 response.data.data 获取 IPage 对象
    const pageData = response.data.data || {};
    errorFiles.value = pageData.records || [];
    totalRecords.value = pageData.total || 0;
  } catch (error) {
    ElMessage.error('获取格式错误文件失败：' + (error.message || '未知错误'));
    errorFiles.value = [];
    totalRecords.value = 0;
  }
};

// 刷新未完成文件列表
const refreshPendingList = () => {
  fetchPendingFiles(currentPage.value, pageSize.value);
  ElMessage.success('列表已刷新');
};

// 删除文件
const deleteFile = (file) => {
  ElMessageBox.confirm(
    '确定要删除该文件吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await deleteFileApi(file.id);
    if (activeTab.value === 'pending') {
      fetchPendingFiles(currentPage.value, pageSize.value);
    } else if (activeTab.value === 'error') {
      fetchErrorFiles(currentPage.value, pageSize.value);
    }
    ElMessage.success('文件已删除');
  }).catch(() => {});
};

// 下载文件
const downloadFile = async (file) => {
  try {
    const response = await downloadFileApi(file.id);
    const blob = new Blob([response.data]);
    const link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = file.fileName;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    ElMessage.success('开始下载文件');
  } catch (error) {
    ElMessage.error('下载失败：' + (error.message || '未知错误'));
  }
};

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val;
  currentPage.value = 1; // 改变分页大小后，重置到第一页
  fetchDataByTab();
};

// 分页页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchDataByTab();
};

// 根据当前标签页获取数据
const fetchDataByTab = () => {
  if (activeTab.value === 'pending') {
    fetchPendingFiles(currentPage.value, pageSize.value);
  } else if (activeTab.value === 'completed') {
    fetchCompletedFiles(currentPage.value, pageSize.value);
  } else if (activeTab.value === 'error') {
    fetchErrorFiles(currentPage.value, pageSize.value);
  }
};

// 监听标签页切换
const handleTabClick = () => {
  currentPage.value = 1; // 切换标签页时，重置到第一页
  fetchDataByTab();
};

// 页面加载时初始化数据
onMounted(() => {
  fetchDataByTab();
});
  </script>
  
  <style lang="scss" scoped>
  .export-container {
  padding: 24px;

  .export-card {
    border-radius: 12px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
    min-height: 600px;

    :deep(.el-card__header) {
      padding: 20px 24px;
      border-bottom: 1px solid #e6e8eb;
    }
  }

  .card-header {
    display: flex;
    align-items: center;
    font-size: 18px;
    font-weight: 600;
    
    .header-icon {
      margin-right: 10px;
    }
  }

  .processing-info {
    margin-bottom: 15px;
    
    .info-content {
      line-height: 1.5;
    }
  }

  .export-tabs {
    :deep(.el-tabs__header) {
      margin-bottom: 24px;
    }
  }

  .table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;

    .header-left {
      display: flex;
      align-items: center;
      gap: 8px;
      color: #1f2937;
      font-weight: 500;

      .el-icon {
        font-size: 20px;
        color: #1a73e8;
      }
    }

    .refresh-btn {
      display: flex;
      align-items: center;
      gap: 4px;
      cursor: pointer;
      padding: 6px 12px;
      border-radius: 6px;
      color: #1a73e8;
      transition: all 0.3s ease;

      &:hover {
        background: rgba(26, 115, 232, 0.08);
      }
    }
  }

  .file-name {
    display: flex;
    align-items: center;
    gap: 8px;

    .el-icon {
      color: #64748b;
    }
  }

  .status-cell {
    width: 150px;
  }

  .count-text {
    font-weight: 500;
    color: #1f2937;
  }

  .error-text {
    color: #dc2626;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    padding: 0 24px 24px;
  }
  }
  </style>